package com.sky.task;


import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/*
 * 订单定时任务
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理支付超时订单一分钟执行一次
     */
    @Transactional
    @Scheduled(cron = "0 0/1 * * * ? ")
    public void processTimeoutOrder() {
        log.info("处理支付超时订单：{}", LocalDateTime.now());
        //查出待支付而且超时的订单
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = orderMapper.list(Orders.PENDING_PAYMENT, time);
        if (ordersList != null && ordersList.size() > 0) {
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("订单支付超时自动取消");
                orderMapper.update(orders);
            });

        }
    }

    /**
     * 处理“派送中”状态的订单每天凌晨一点执行一次
     */
    @Transactional
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder() {
        //派送中的订单
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.list(Orders.DELIVERY_IN_PROGRESS, time);
        if (ordersList != null && ordersList.size() > 0) {
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                orders.setCheckoutTime(LocalDateTime.now());
                orders.setDeliveryTime(LocalDateTime.now());
                orderMapper.update(orders);
            });

        }
    }
}
